package servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 登录Servlet
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得参数
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        //调用service对象执行登录
        UserService userService = new UserServiceImpl();
        try {
            User user = userService.login(username, pwd);
            if(user == null){
                //将错误信息保存到request对象
                req.setAttribute("error","账号或密码错误");
                //如果登录失败，请求转发到登录页面
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }else{
                //将用户对象保存到session对象
                req.getSession().setAttribute("user",user);
                //如果登录成功，重定向到查询手机的servlet
                resp.sendRedirect("/findAllPhones.do");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
